"""
集成演示脚本

演示完整的资源分配流程：
1. 数据加载
2. 资源计算
3. Excel输出
4. 结果分析
"""

import logging
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from src.models.data_models import ProjectInfo, ProjectRole, PhaseDetail
from src.services.resource_calculator import ResourceCalculator
from src.services.data_loader import DataLoader
from src.services.excel_generator import ExcelGenerator


def create_sample_data():
    """
    创建演示用的样例数据
    
    Returns:
        tuple: (projects, project_roles, phases)
    """
    print("创建演示样例数据...")
    
    # 创建项目信息
    projects = [
        ProjectInfo(
            project_code="PRJ001",
            project_name="电商平台重构项目",
            start_month="2024-01", 
            end_month="2024-08",
            priority=1,
            description="对现有电商平台进行全面重构，提升性能和用户体验"
        ),
        ProjectInfo(
            project_code="PRJ002", 
            project_name="移动端APP开发",
            start_month="2024-03",
            end_month="2024-07",
            priority=2,
            description="开发配套的移动端应用"
        ),
        ProjectInfo(
            project_code="PRJ003",
            project_name="数据分析平台",
            start_month="2024-06",
            end_month="2024-10", 
            priority=3,
            description="构建实时数据分析和报表平台"
        )
    ]
    
    # 创建项目角色需求
    project_roles = [
        # 电商平台重构项目
        ProjectRole("PRJ001", "项目经理", 1, ["项目管理", "沟通协调"], "高级"),
        ProjectRole("PRJ001", "技术负责人", 1, ["架构设计", "技术选型"], "资深"),
        ProjectRole("PRJ001", "前端开发工程师", 4, ["React", "TypeScript", "CSS3"], "中级"),
        ProjectRole("PRJ001", "后端开发工程师", 6, ["Java", "Spring Boot", "MySQL"], "中级"),
        ProjectRole("PRJ001", "测试工程师", 3, ["自动化测试", "性能测试"], "中级"),
        ProjectRole("PRJ001", "UI设计师", 2, ["UI设计", "用户体验"], "中级"),
        
        # 移动端APP开发
        ProjectRole("PRJ002", "产品经理", 1, ["产品设计", "需求分析"], "高级"),
        ProjectRole("PRJ002", "iOS开发工程师", 3, ["Swift", "Objective-C"], "中级"),
        ProjectRole("PRJ002", "Android开发工程师", 3, ["Kotlin", "Java"], "中级"),
        ProjectRole("PRJ002", "测试工程师", 2, ["移动端测试", "兼容性测试"], "中级"),
        ProjectRole("PRJ002", "UI设计师", 1, ["移动端UI", "交互设计"], "高级"),
        
        # 数据分析平台（故意缺少测试角色来演示边界情况）
        ProjectRole("PRJ003", "数据架构师", 1, ["数据建模", "ETL设计"], "资深"),
        ProjectRole("PRJ003", "后端开发工程师", 4, ["Python", "Spark", "Kafka"], "中级"),
        ProjectRole("PRJ003", "前端开发工程师", 2, ["Vue", "ECharts", "D3.js"], "中级")
        # 注意：这里故意没有测试工程师来演示算法的处理能力
    ]
    
    # 创建阶段详细信息
    phases = [
        # 电商平台重构项目的阶段
        PhaseDetail(
            project_code="PRJ001",
            phase_name="需求分析与设计",
            start_month="2024-01",
            end_month="2024-02",
            role_allocations={
                "项目经理": 1,
                "技术负责人": 1,
                "UI设计师": 2,
                "前端开发工程师": 1,
                "后端开发工程师": 1
            },
            dependencies=[],
            deliverables=["需求文档", "技术方案", "UI设计稿"]
        ),
        PhaseDetail(
            project_code="PRJ001", 
            phase_name="核心功能开发",
            start_month="2024-03",
            end_month="2024-06",
            role_allocations={
                "前端开发工程师": 4,
                "后端开发工程师": 6,
                "技术负责人": 1
            },
            dependencies=["需求分析与设计"],
            deliverables=["核心功能代码", "API文档"]
        ),
        PhaseDetail(
            project_code="PRJ001",
            phase_name="测试与优化",
            start_month="2024-06",
            end_month="2024-08",
            role_allocations={
                "测试工程师": 3,
                "前端开发工程师": 2,
                "后端开发工程师": 3
            },
            dependencies=["核心功能开发"],
            deliverables=["测试报告", "性能优化方案"]
        ),
        
        # 移动端APP开发的阶段
        PhaseDetail(
            project_code="PRJ002",
            phase_name="产品设计",
            start_month="2024-03",
            end_month="2024-03",
            role_allocations={
                "产品经理": 1,
                "UI设计师": 1
            },
            dependencies=[],
            deliverables=["产品原型", "UI设计"]
        ),
        PhaseDetail(
            project_code="PRJ002",
            phase_name="应用开发",
            start_month="2024-04", 
            end_month="2024-06",
            role_allocations={
                "iOS开发工程师": 3,
                "Android开发工程师": 3,
                "产品经理": 1
            },
            dependencies=["产品设计"],
            deliverables=["iOS应用", "Android应用"]
        ),
        PhaseDetail(
            project_code="PRJ002",
            phase_name="测试发布",
            start_month="2024-06",
            end_month="2024-07",
            role_allocations={
                "测试工程师": 2,
                "iOS开发工程师": 1,
                "Android开发工程师": 1
            },
            dependencies=["应用开发"],
            deliverables=["测试报告", "应用商店发布"]
        ),
        
        # 数据分析平台的阶段（重叠演示）
        PhaseDetail(
            project_code="PRJ003",
            phase_name="数据架构设计",
            start_month="2024-06",
            end_month="2024-07",
            role_allocations={
                "数据架构师": 1,
                "后端开发工程师": 2
            },
            dependencies=[],
            deliverables=["数据架构文档", "ETL方案"]
        ),
        PhaseDetail(
            project_code="PRJ003", 
            phase_name="平台开发",
            start_month="2024-07",
            end_month="2024-09",
            role_allocations={
                "后端开发工程师": 4,
                "前端开发工程师": 2,
                "数据架构师": 1
            },
            dependencies=["数据架构设计"],
            deliverables=["数据处理引擎", "可视化界面"]
        ),
        PhaseDetail(
            project_code="PRJ003",
            phase_name="系统集成",
            start_month="2024-09",
            end_month="2024-10",
            role_allocations={
                "后端开发工程师": 2,
                "前端开发工程师": 1
            },
            dependencies=["平台开发"],
            deliverables=["集成测试报告", "部署文档"]
        )
    ]
    
    return projects, project_roles, phases


def analyze_results(allocations, projects, project_roles, phases):
    """
    分析计算结果
    
    Args:
        allocations: 月度分配结果
        projects: 项目信息
        project_roles: 项目角色
        phases: 阶段详情
    """
    print("\n=== 结果分析 ===")
    
    # 1. 基本统计
    total_allocations = len(allocations)
    unique_months = len(set(a.month for a in allocations))
    unique_projects = len(set(a.project_code for a in allocations))
    unique_roles = len(set(a.role_name for a in allocations))
    
    print(f"总分配记录数: {total_allocations}")
    print(f"涉及月份数: {unique_months}")
    print(f"涉及项目数: {unique_projects}")
    print(f"涉及角色数: {unique_roles}")
    
    # 2. 角色分布统计
    print("\n角色分布统计:")
    role_stats = {}
    for allocation in allocations:
        role = allocation.role_name
        if role not in role_stats:
            role_stats[role] = {"required": 0, "allocated": 0, "months": 0}
        role_stats[role]["required"] += allocation.required_count
        role_stats[role]["allocated"] += allocation.allocated_count
        role_stats[role]["months"] += 1
    
    for role, stats in sorted(role_stats.items()):
        utilization = (stats["allocated"] / stats["required"] * 100) if stats["required"] > 0 else 0
        print(f"  {role}: 需求{stats['required']}人月, 分配{stats['allocated']}人月, "
              f"利用率{utilization:.1f}%, 涉及{stats['months']}个月")
    
    # 3. 项目维度统计
    print("\n项目维度统计:")
    project_stats = {}
    for allocation in allocations:
        project = allocation.project_code
        if project not in project_stats:
            project_stats[project] = {"required": 0, "allocated": 0}
        project_stats[project]["required"] += allocation.required_count
        project_stats[project]["allocated"] += allocation.allocated_count
    
    project_name_map = {p.project_code: p.project_name for p in projects}
    
    for project_code, stats in sorted(project_stats.items()):
        project_name = project_name_map.get(project_code, project_code)
        utilization = (stats["allocated"] / stats["required"] * 100) if stats["required"] > 0 else 0
        print(f"  {project_code} ({project_name}): 需求{stats['required']}人月, "
              f"分配{stats['allocated']}人月, 利用率{utilization:.1f}%")
    
    # 4. 月度峰值分析
    print("\n月度峰值分析:")
    monthly_totals = {}
    for allocation in allocations:
        month = allocation.month
        if month not in monthly_totals:
            monthly_totals[month] = 0
        monthly_totals[month] += allocation.allocated_count
    
    for month in sorted(monthly_totals.keys()):
        total = monthly_totals[month]
        print(f"  {month}: {total}人")
    
    # 5. 检查特殊情况
    print("\n特殊情况检查:")
    
    # 检查自动生成的TL
    tl_allocations = [a for a in allocations if a.role_name == 'TL']
    if tl_allocations:
        total_tl = sum(a.allocated_count for a in tl_allocations)
        print(f"  [OK] 自动生成了{total_tl}个TL人月的分配")
    
    # 检查缺少测试角色的项目
    project_roles_map = {}
    for role in project_roles:
        if role.project_code not in project_roles_map:
            project_roles_map[role.project_code] = []
        project_roles_map[role.project_code].append(role.role_name)
    
    for project in projects:
        roles = project_roles_map.get(project.project_code, [])
        has_tester = any("测试" in role for role in roles)
        if not has_tester:
            print(f"  [WARN] 项目{project.project_code}缺少测试角色，算法正常处理")
    
    # 6. 资源冲突检查
    print("\n资源冲突检查:")
    monthly_role_demand = {}
    for allocation in allocations:
        key = (allocation.month, allocation.role_name)
        if key not in monthly_role_demand:
            monthly_role_demand[key] = 0
        monthly_role_demand[key] += allocation.allocated_count
    
    conflict_months = []
    for (month, role), demand in monthly_role_demand.items():
        if demand > 10:  # 假设单个角色月需求超过10人可能存在资源冲突
            conflict_months.append((month, role, demand))
    
    if conflict_months:
        print("  可能的资源冲突:")
        for month, role, demand in conflict_months:
            print(f"    {month} {role}: {demand}人 (可能需要关注)")
    else:
        print("  [OK] 未发现明显的资源冲突")


def main():
    """主函数"""
    print("=== 资源分配系统集成演示 ===")
    
    # 配置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    try:
        # 1. 创建演示数据
        projects, project_roles, phases = create_sample_data()
        print(f"[OK] 创建演示数据: {len(projects)}个项目, {len(project_roles)}个角色需求, {len(phases)}个阶段")
        
        # 2. 初始化计算器
        calculator = ResourceCalculator(tl_ratio=0.15)  # 设置15%的TL配比
        print("[OK] 初始化资源计算器")
        
        # 3. 执行资源分配计算
        print("\n开始执行资源分配计算...")
        allocations = calculator.calculate_monthly_allocations(projects, project_roles, phases)
        print(f"[OK] 计算完成，生成{len(allocations)}条月度分配记录")
        
        # 4. 分析结果
        analyze_results(allocations, projects, project_roles, phases)
        
        # 5. 生成Excel报告
        print("\n生成Excel报告...")
        excel_generator = ExcelGenerator()
        output_path = "D:/Project/auto-resource-plan/data/integration_demo_report.xlsx"
        
        excel_generator.generate_resource_plan_excel(
            allocations=allocations,
            projects=projects,
            project_roles=project_roles,
            phases=phases,
            output_path=output_path
        )
        print(f"[OK] Excel报告已生成: {output_path}")
        
        # 6. 生成汇总报告
        print("\n生成汇总分析...")
        resource_summary = calculator.get_resource_summary(allocations)
        project_summary = calculator.get_project_summary(allocations)
        utilization_rates = calculator.calculate_utilization_rate(allocations)
        resource_gaps = calculator.identify_resource_gaps(allocations)
        
        print("\n月度资源汇总 (前5个月):")
        for month in sorted(resource_summary.keys())[:5]:
            roles = resource_summary[month]
            total = sum(roles.values())
            print(f"  {month}: 总计{total}人 ({', '.join(f'{r}:{c}人' for r, c in sorted(roles.items()))})")
        
        print("\n资源利用率:")
        for role, rate in sorted(utilization_rates.items()):
            status = "[OK]" if rate >= 0.9 else "[WARN]" if rate >= 0.7 else "[ERROR]"
            print(f"  {status} {role}: {rate*100:.1f}%")
        
        if resource_gaps:
            print(f"\n资源缺口 (前5项):")
            for gap in resource_gaps[:5]:
                print(f"  {gap['month']} {gap['project_code']} {gap['role_name']}: 缺口{gap['shortage']}人")
        else:
            print("\n[OK] 未发现资源缺口")
        
        print("\n=== 演示完成 ===")
        print(f"所有功能正常工作，详细结果请查看: {output_path}")
        
    except Exception as e:
        print(f"演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True


if __name__ == "__main__":
    success = main()
    exit(0 if success else 1)